package com.rfsp.common.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rfsp.common.base.BaseService;
import com.rfsp.common.mapper.AreaMapper;
import com.rfsp.common.pojo.po.AreaPO;
import com.rfsp.common.pojo.vo.AreaVO;
import com.rfsp.common.cache.AreaCache;

@Service
public class AreaService extends BaseService<AreaPO>{
	
	public Logger logger = LoggerFactory.getLogger(AreaService.class);
	
	@Autowired
	AreaMapper areaMapper;
	
	@Autowired
	AreaCache areaCache;
	
	public List<AreaVO> queryAllAreas() {
        return areaMapper.queryAll();
	}
	
	public List<AreaVO> getChild(String uppCode) {
		return getAreaVO(uppCode).getChildren();
	}

	public String getFullAddress(String areaCode){
		logger.info("getFullAddress START");

		StringBuilder sb = new StringBuilder();
		if(StringUtils.isBlank(areaCode) || "000000".equals(areaCode)) {
			sb.append("全国");
		}else if(areaCode.endsWith("0000")) {
			sb.append(getAreaName(areaCode));
		}else if(areaCode.endsWith("00")){
			sb.append(getParentVO(areaCode).getText()).append("-").append(getAreaName(areaCode));
		}else {
			AreaVO parentVO = getParentVO(areaCode);
			if (parentVO == null) {
				return areaCode;
			}
			sb.append(getParentVO(getParentVO(areaCode)).getText()).append("-").append(getParentVO(areaCode).getText()).append("-").append(getAreaName(areaCode));
		}

		logger.info("getFullAddress END");
		return sb.toString();
	}

	public String getAreaName(String areaCode) {
		return getAreaVO(areaCode).getText();
	}

	public AreaVO getAreaVO(String areaCode) {
		return areaCache.areaMap.get(areaCode);
	}

	public AreaVO getParentVO(String areaCode) {
		AreaVO areaVO = getAreaVO(areaCode);
		if (areaVO == null) {
			return null;
		}
		return areaCache.areaMap.get(areaVO.getParent());
	}

	public AreaVO getParentVO(AreaVO vo) {
		return getParentVO(vo.getId());
	}

	public AreaPO getAreaByCode(String areaCode){
		return areaMapper.getAreaByCode(areaCode);
	}

}
